package main

import (
	"fmt"
	"time"
)

//使用goroutines和channels 来实现一个工作池
//工人将在jobs渠道上接受工作并发送相应的结果results
func work(id int, jobs <-chan int, results chan<- int) {
	for j := range jobs {
		fmt.Println("worker ", id, "started job ", j)
		time.Sleep(time.Second)
		fmt.Println("worker ", id, "finished job ", j)
		results <- id * j
	}
}

func main() {

	jobs := make(chan int, 100)
	results := make(chan int, 100)
	//启动了3名工人，最初因为没有工作而被锁
	for w := 1; w <= 3; w++ {
		go work(w, jobs, results)
	}
	//发送5 jobs，然后发送close该频道，以s示所有的工作。
	for j := 1; j <= 5; j++ {
		jobs <- j
	}
	close(jobs)
	//收集工作的所有结果
	for a := 1; a <= 5; a++ {
		<-results
	}
}
